<template>
  <div>
    <div class="table-layout">
      <el-card shadow="never">
        <div class="table-handle">
          <el-button type="primary" size="mini" icon="el-icon-plus" @click="onAdd">新增分类</el-button>
          <el-radio-group v-model="currentType" @change="handleTypeChange" style="margin-left: 20px;">
            <el-radio-button label="物资">物资</el-radio-button>
            <el-radio-button label="设备">设备</el-radio-button>
          </el-radio-group>
        </div>
        <div class="table-box">
          <el-table
            size="large"
            stripe
            border
            v-loading="loading"
            max-height="500px"
            :data="tableData"
            row-key="id"
            :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
            default-expand-all
            element-loading-spinner="el-icon-loading"
            element-loading-background="rgba(255, 255, 255, 0.8)"
            @selection-change="onSelect"
          >
            <el-table-column label="分类名称" prop="name" />
            <el-table-column label="分类类型" align="center" width="120">
              <template #default="scope">
                <el-tag v-if="scope.row.type === '物资'" type="success">物资</el-tag>
                <el-tag v-else-if="scope.row.type === '设备'" type="primary">设备</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="排序" align="center" prop="sort" width="80" />
            <el-table-column label="操作" fixed="right" width="220px">
              <template slot-scope="scope">
                <el-button type="text" @click="onAddSub(scope.row)" v-if="!scope.row.parent_id">添加子分类</el-button>
                <el-button type="text" @click="onEdit(scope.row)">编辑</el-button>
                <el-button type="text" style="color: #F82222" @click="onDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>
    </div>

    <!-- 添加/编辑分类弹窗 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px" @close="resetForm">
      <el-form :model="form" :rules="rules" ref="form" label-width="100px">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入分类名称"></el-input>
        </el-form-item>
        <el-form-item label="分类类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择分类类型" style="width: 100%">
            <el-option label="物资" value="物资"></el-option>
            <el-option label="设备" value="设备"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :min="0" :max="999" style="width: 100%"></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { http } from "@/api";

export default {
  name: "IdleCategory",
  data() {
    return {
      loading: false,
      tableData: [],
      currentType: '物资',

      // 弹窗相关
      dialogVisible: false,
      dialogTitle: '新增分类',
      isEdit: false,
      form: {
        name: '',
        type: '物资',
        sub_type: '',
        parent_id: 0,
        sort: 0
      },
      rules: {
        name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择分类类型', trigger: 'change' }
        ]
      }
    };
  },
  created() {
    this.fetchData();
  },
  methods: {
    fetchData() {
      this.loading = true;
      http.idleCategory.tree({ type: this.currentType }).then(res => {
        this.tableData = res.data;
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },

    handleTypeChange() {
      this.fetchData();
    },

    onAdd() {
      this.dialogTitle = '新增分类';
      this.isEdit = false;
      this.form = {
        name: '',
        type: this.currentType,
        sub_type: '',
        parent_id: 0,
        sort: 0
      };
      this.dialogVisible = true;
    },

    onAddSub(row) {
      this.dialogTitle = '新增子分类';
      this.isEdit = false;
      this.form = {
        name: '',
        type: row.type,
        sub_type: row.sub_type || '',
        parent_id: row.id,
        sort: 0
      };
      this.dialogVisible = true;
    },

    onEdit(row) {
      this.dialogTitle = '编辑分类';
      this.isEdit = true;
      this.form = { ...row };
      this.dialogVisible = true;
    },

    onDelete(row) {
      this.$confirm('确认删除该分类吗？删除后不可恢复', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        http.idleCategory.delete(row.id).then(() => {
          this.$message.success('删除成功');
          this.fetchData();
        }).catch(error => {
          this.$message.error(error.message || '删除失败');
        });
      }).catch(() => {});
    },

    onSelect(selection) {
      this.selection = selection;
    },

    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.isEdit) {
            // 编辑
            const id = this.form.id;
            http.idleCategory.update(id, this.form).then(() => {
              this.$message.success('更新成功');
              this.dialogVisible = false;
              this.fetchData();
            }).catch(error => {
              this.$message.error(error.message || '更新失败');
            });
          } else {
            // 新增
            http.idleCategory.create(null, this.form).then(() => {
              this.$message.success('添加成功');
              this.dialogVisible = false;
              this.fetchData();
            }).catch(error => {
              this.$message.error(error.message || '添加失败');
            });
          }
        }
      });
    },

    resetForm() {
      if (this.$refs.form) {
        this.$refs.form.resetFields();
      }
    }
  }
};
</script>

<style scoped>
.table-layout {
  margin-top: 20px;
}
.table-handle {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}
.table-box {
  margin-bottom: 20px;
}
</style>
